﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumBill;
using PARK.Consumer.Interfaces.ConsumAdjust;
using PARK.Consumer.Interfaces.ConsumBill;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using PARK.JsonSerialization;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace PARK.Consumer
{
    /// <summary>
    /// 消费调账记录
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "Adjust", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumAdjustService : IConsumAdjustService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumAdjustEntity> _consumAdjustRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumAdjustService"/>类型的新实例
        /// </summary>
        public ConsumAdjustService(
            ISqlSugarRepository<ConsumAdjustEntity> consumAdjustRepository,
            IUserManager userManager)
        {
            _consumAdjustRepository = consumAdjustRepository;
            _db = consumAdjustRepository.Context;
            _userManager = userManager;
        }

        #region Get
        /// <summary>
        /// 获取调账详细
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            StringBuilder dbSql = new StringBuilder("select a.Id as Id, a.BillId,a.txnTotalAmt,a.AdjustAmt,a.AjtAccConsAmt,a.AjtAccBalBef,a.AjtAccBalAfter,a.AjtWelfareConsAmt,a.AjtWelfareBalBef,a.AjtWelfareBalAfter,a.AjtDate,a.AjtUser,a.ajtUserName,");
            dbSql.Append(" b.machineId,b.machineNo,b.machineName,b.merchantCode,b.merchantName,b.cardNo,b.catCardNo,");
            dbSql.Append(" b.employeeId,b.jobNo,b.reallName,b.departName,b.txnSeq,b.txnDate,b.txnResult,b.requestId,b.payWay,b.uploadTime");
            dbSql.Append(" from consum_adjust a");
            dbSql.Append(" inner join consum_bill b  on a.BillId=b.Id");
            dbSql.AppendFormat(" and b.CompanyId='{0}'", userInfo.companyId);
            dbSql.AppendFormat(" and a.Id='{0}'", id);
            var data = await _db.SqlQueryable<ConsumAdjustListOutput>(dbSql.ToString()).Select(it => new ConsumAdjustListOutput
            {
                id=it.id,
                machineId =it.machineId,
                machineNo =it.machineNo,
                machineName =it.machineName,
                merchantCode = it.merchantCode,
                merchantName = it.merchantName,
                cardNo = it.cardNo,
                catCardNo = it.catCardNo,
                employeeId = it.employeeId,
                jobNo = it.jobNo,
                reallName = it.reallName,
                departName = it.departName,
                txnTotalAmt = it.txnTotalAmt,
                txnSeq = it.txnSeq,
                txnDate = it.txnDate,
                txnResult = it.txnResult,
                requestId = it.requestId,
                payWay = it.payWay,
                uploadTime = it.uploadTime,
                adjustAmt = it.adjustAmt,
                ajtAccConsAmt = it.ajtAccConsAmt,
                ajtAccBalBef = it.ajtAccBalBef,
                ajtAccBalAfter = it.ajtAccBalAfter,
                ajtWelfareConsAmt = it.ajtWelfareConsAmt,
                ajtWelfareBalBef = it.ajtWelfareBalBef,
                ajtWelfareBalAfter = it.ajtWelfareBalAfter,
                ajtDate = it.ajtDate,
                ajtUser = it.ajtUser,
                ajtUserName = it.ajtUserName

            }).ToListAsync();
            var output = data[0].Adapt<ConsumBillInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取调账记录列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumAdjustListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                if (input.departId == userInfo.companyId)
                {
                    input.departId = null;
                }
                var sidx = input.sidx == null ? "AjtDate" : input.sidx;
                List<string> queryAjtDate = input.ajtDate != null ? input.ajtDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startAjtDate = queryAjtDate != null ? Ext.GetDateTime(queryAjtDate.First()) : null;
                DateTime? endAjtDate = queryAjtDate != null ? Ext.GetDateTime(queryAjtDate.Last()) : null;

                List<string> queryTxnDate = input.txnDate != null ? input.txnDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startTxnDate = queryTxnDate != null ? Ext.GetDateTime(queryTxnDate.First()) : null;
                DateTime? endTxnDate = queryTxnDate != null ? Ext.GetDateTime(queryTxnDate.Last()) : null;

                StringBuilder dbSql = new StringBuilder("select a.Id as Id, a.BillId,a.txnTotalAmt,a.AdjustAmt,a.AjtAccConsAmt,a.AjtAccBalBef,a.AjtAccBalAfter,a.AjtWelfareConsAmt,a.AjtWelfareBalBef,a.AjtWelfareBalAfter,a.AjtDate,a.AjtUser,a.ajtUserName,");
                dbSql.Append(" b.machineId,b.machineNo,b.machineName,b.merchantCode,b.merchantName,b.cardNo,b.catCardNo,");
                dbSql.Append(" b.employeeId,b.jobNo,b.reallName,b.departName,b.txnSeq,b.txnDate,b.txnResult,b.requestId,b.payWay,b.uploadTime");
                dbSql.Append(" from consum_adjust a");
                dbSql.Append(" inner join consum_bill b  on a.BillId=b.Id");
                dbSql.AppendFormat(" and b.CompanyId='{0}'", userInfo.companyId);
                //调账时间查询
                if (!string.IsNullOrEmpty(input.ajtDate))
                {
                    var _startAjtDate = (new DateTime(startAjtDate.ToDate().Year, startAjtDate.ToDate().Month, startAjtDate.ToDate().Day, 0, 0, 0));
                    var _endAjtDate = (new DateTime(endAjtDate.ToDate().Year, endAjtDate.ToDate().Month, endAjtDate.ToDate().Day, 23, 59, 59));
                    dbSql.AppendFormat(" and a.AjtDate>='{0}'", _startAjtDate);
                    dbSql.AppendFormat(" and a.AjtDate<='{0}'", _endAjtDate);
                }
                //消费时间查询
                if (!string.IsNullOrEmpty(input.txnDate))
                {
                    var _starttxnDate = (new DateTime(startTxnDate.ToDate().Year, startTxnDate.ToDate().Month, startTxnDate.ToDate().Day, 0, 0, 0));
                    var _endtxnDate = (new DateTime(endTxnDate.ToDate().Year, endTxnDate.ToDate().Month, endTxnDate.ToDate().Day, 23, 59, 59));
                    dbSql.AppendFormat(" and b.txnDate>='{0}'", _starttxnDate);
                    dbSql.AppendFormat(" and b.txnDate<='{0}'", _endtxnDate);
                }
                //消费卡号查询
                if (!string.IsNullOrEmpty(input.cardNo))
                {
                    dbSql.AppendFormat(" and b.CardNo='{0}'", input.cardNo);
                }
                //关键字查询
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    dbSql.AppendFormat(" and (b.JobNo='{0}' or b.ReallName='{0}' or b.CatCardNo='{0}')", input.keyword);
                }
                //消费机名称查询
                if (!string.IsNullOrEmpty(input.machineName))         
                {
                    dbSql.AppendFormat(" and b.MachineId='{0}'", input.machineId);
                }
                //商户名称查询
                if (!string.IsNullOrEmpty(input.merchantName))
                {
                    dbSql.AppendFormat(" and b.MerchantId='{0}'", input.merchantId);
                }
                //姓名查询
                if (!string.IsNullOrEmpty(input.reallName))
                {
                    dbSql.AppendFormat(" and b.ReallName='{0}'", input.reallName);
                }
                //部门查询
                if (!string.IsNullOrEmpty(input.departId))
                {
                    dbSql.AppendFormat(" and b.DepartId='{0}'", input.departId);
                }
                var data = await _db.SqlQueryable<ConsumAdjustListOutput>(dbSql.ToString()).Select(it => new ConsumAdjustListOutput
                {
                    id = it.id,
                    merchantName = it.merchantName,
                    cardNo = it.cardNo,
                    employeeId = it.employeeId,
                    jobNo = it.jobNo,
                    reallName = it.reallName,
                    departName = it.departName,
                    txnTotalAmt = it.txnTotalAmt,
                    txnSeq = it.txnSeq,
                    txnDate = it.txnDate,
                    txnResult = it.txnResult,
                    requestId = it.requestId,
                    payWay = it.payWay,
                    uploadTime = it.uploadTime,
                    adjustAmt =it.adjustAmt,
                    ajtAccConsAmt=it.ajtAccConsAmt,
                    ajtAccBalBef=it.ajtAccBalBef,
                    ajtAccBalAfter=it.ajtAccBalAfter,
                    ajtWelfareConsAmt=it.ajtWelfareConsAmt,
                    ajtWelfareBalBef=it.ajtWelfareBalBef,
                    ajtWelfareBalAfter=it.ajtWelfareBalAfter,
                    ajtDate=it.ajtDate,
                    ajtUser = it.ajtUser,
                    ajtUserName = it.ajtUserName,
                    catCardNo = it.catCardNo

                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumAdjustListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加消费调账
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ConsumAdjustCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<ConsumBillEntity>().FirstAsync(p => p.Id == input.billId);
                if (entity != null)
                {
                    var Paras = new List<SugarParameter>();
                    Paras.Add(new SugarParameter("@billId", input.billId));
                    Paras.Add(new SugarParameter("@adjustAmt", input.adjustAmt));
                    Paras.Add(new SugarParameter("@upflag", null, true));
                    Paras.Add(new SugarParameter("@AjtUser", userInfo.userId));
                    Paras.Add(new SugarParameter("@AjtUserName", userInfo.userName));
                    _db.Ado.UseStoredProcedure().ExecuteCommand("P_ConsumAdjust_Add", Paras);
                    object _obj = Paras[2].Value;
                    if (_obj == null || int.Parse(_obj.ToString()) < 1)
                        throw PARKException.Bah("消费调账失败!");
                }
                else
                {
                    throw PARKException.Bah("参数错误,调账失败!");
                }
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        #endregion
    }
}
